package org.example.volunteerend.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.example.volunteerend.dto.PageResponse;
import org.example.volunteerend.entity.ImageStorage;
import org.example.volunteerend.mapper.ImageStorageMapper;
import org.example.volunteerend.service.ImageService;
import org.example.volunteerend.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

@Service
public class ImageServiceImpl implements ImageService {

    private final ImageStorageMapper imageStorageMapper;
    
    @Autowired
    public ImageServiceImpl(ImageStorageMapper imageStorageMapper) {
        this.imageStorageMapper = imageStorageMapper;
    }
    
    @Override
    @Transactional
    public Map<String, Object> uploadImage(MultipartFile image, Integer userId, String imageType) throws Exception {
        // 校验文件
        if (image == null || image.isEmpty()) {
            throw new IllegalArgumentException("图片不能为空");
        }
        
        // 校验图片类型
        if (!isValidImageType(imageType)) {
            throw new IllegalArgumentException("无效的图片类型，请使用：avatar, project, service_proof, other");
        }
        
        // 获取文件扩展名
        String originalFilename = image.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        
        // 构建OSS存储路径
        String filename = "images/" + imageType + "/" + userId + "/" + UUID.randomUUID().toString() + extension;
        
        // 上传到阿里云OSS
        String imageUrl = AliOssUtil.uploadFile(filename, image.getInputStream());
        
        // 保存图片记录
        ImageStorage imageStorage = new ImageStorage();
        imageStorage.setUserId(userId);
        imageStorage.setImageUrl(imageUrl);
        imageStorage.setImageType(imageType);
        
        imageStorageMapper.insert(imageStorage);
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("image_id", imageStorage.getImageId());
        result.put("image_url", imageStorage.getImageUrl());
        result.put("upload_time", imageStorage.getUploadTime());
        
        return result;
    }
    
    @Override
    @Transactional
    public boolean deleteImage(Integer imageId) {
        // 查询图片记录
        ImageStorage image = imageStorageMapper.findById(imageId);
        if (image == null) {
            throw new IllegalArgumentException("图片不存在");
        }
        
        // 删除图片记录
        int rows = imageStorageMapper.delete(imageId);
        
        // TODO: 如果需要的话，从阿里云OSS中删除文件
        // 此处未实现从OSS删除的功能，因为权限考虑，通常只在数据库中删除记录
        
        return rows > 0;
    }
    
    @Override
    public PageResponse<Map<String, Object>> getUserImages(Integer userId, String imageType, Integer page, Integer pageSize) {
        // 设置默认值
        if (page == null || page < 1) {
            page = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        
        // 查询用户图片列表
        List<ImageStorage> images = imageStorageMapper.findByUserId(userId, imageType);
        
        // 统计总数
        int total = imageStorageMapper.countByUserId(userId, imageType);
        
        // 手动分页
        int start = (page - 1) * pageSize;
        int end = Math.min(start + pageSize, images.size());
        
        List<ImageStorage> pagedImages = start < end ? images.subList(start, end) : new ArrayList<>();
        
        // 转换为返回格式
        List<Map<String, Object>> rows = new ArrayList<>();
        for (ImageStorage image : pagedImages) {
            Map<String, Object> item = new HashMap<>();
            item.put("image_id", image.getImageId());
            item.put("image_url", image.getImageUrl());
            item.put("image_type", image.getImageType());
            item.put("upload_time", image.getUploadTime());
            rows.add(item);
        }
        
        return new PageResponse<>(rows, total, page, pageSize);
    }
    
    /**
     * 校验图片类型是否有效
     */
    private boolean isValidImageType(String imageType) {
        return "avatar".equals(imageType) || 
               "project".equals(imageType) || 
               "service_proof".equals(imageType) || 
               "other".equals(imageType);
    }
} 